package com.sds.prolog.dao;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.sds.prolog.interpreter.InterpreterUtils;
import com.sds.prolog.model.PrologSystemInfo;
import com.sds.system.daos.AbstractDAO;
import com.sds.system.models.IdentifiedObject;
import com.sds.prolog.model.Laptop;
import com.sds.prolog.model.Question;
import com.sds.prolog.model.Rule;
import com.sds.system.helpers.ResourceUtils;

import javax.persistence.EntityManagerFactory;
import java.io.InputStream;
import java.util.List;
import java.util.logging.Logger;

@Singleton
public class PrologDAO extends AbstractDAO {

    private Logger logger = Logger.getLogger(getClass().getName());
    private static String PROLOG_SYSTEM_ID = "prolog-system";


    @Inject
    public PrologDAO(EntityManagerFactory emf) {
        super(emf);
        logger.info("Prolog DAO service started!");
    }

    public void parseAndUpdate(InputStream input) {
        List<String> lines = ResourceUtils.readLinesIgnoringComment(input);
        for (String line : lines) {
            IdentifiedObject object = InterpreterUtils.interpret(line);
            if (object instanceof Laptop) {
                getObjectManager(Laptop.class).store((Laptop) object).perform();
            } else if (object instanceof Rule) {
                getObjectManager(Rule.class).store((Rule) object).perform();
            } else if (object instanceof Question) {
                getObjectManager(Question.class).store((Question) object).perform();
            }
        }
    }

    public PrologSystemInfo getSystemInfo() {
        PrologSystemInfo prologSystemInfo = getObjectManager(PrologSystemInfo.class).findById(PROLOG_SYSTEM_ID).perform().getSingleResult();
        if (prologSystemInfo == null) {
            prologSystemInfo = new PrologSystemInfo();
            prologSystemInfo.setId(PROLOG_SYSTEM_ID);
            getObjectManager(PrologSystemInfo.class).store(prologSystemInfo).perform();
        }
        return prologSystemInfo;
    }

    public void saveSystemInfo(PrologSystemInfo prologSystemInfo) {
        getObjectManager(PrologSystemInfo.class).store(prologSystemInfo.createClone()).perform();
    }
}
